package com.liang.blog.security.utils;

import com.liang.blog.model.constant.SecurityConstants;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.apache.commons.lang3.StringUtils;

import javax.swing.plaf.PanelUI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取当前线程变量中的 用户id、Token等信息
 *
 * @Author：YanWenLiang
 * @Date:2023-08-23-22:15
 */
public class BlogSecurityUtil {
    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();



    public static Long getUserId() {
        return Long.parseLong(get(SecurityConstants.DETAILS_USER_ID));
    }

    public static void set(String key, Object value) {
        Map<String, Object> localMap = getLocalMap();
        localMap.put(key, value == null ? StringUtils.EMPTY : value);
    }

    public static String get(String key) {
        return getLocalMap().getOrDefault(key, StringUtils.EMPTY).toString();
    }

    public static <T> T get(String key, Class<T> tClass) {
        return (T) getLocalMap().get(key);
    }



    public static void setUserId(String userId) {
        set(SecurityConstants.DETAILS_USER_ID, userId);
    }

    public static String getAccount() {
        return get(SecurityConstants.DETAILS_ACCOUNT);
    }

    public static void setAccount(String account) {
        set(SecurityConstants.DETAILS_ACCOUNT, account);
    }

    public static String getUserKey() {
        return get(SecurityConstants.USER_KEY);
    }

    public static void setUserKey(String userKey) {
        set(SecurityConstants.USER_KEY, userKey);
    }

    public static String getPermission() {
        return get(SecurityConstants.ROLE_PERMISSION);
    }

    public static void setPermission(String permissions) {
        set(SecurityConstants.ROLE_PERMISSION, permissions);
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }


    /**
     * 获取当前线程独立的 map
     *
     * @return
     */
    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

}
